<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';

    if(!IsValidSession())
    {
        header('Location: login.php?page=index');
        exit();
    }
    else
    {
        RefreshSession();
    }

    masterpage("Edit Course Instance");

    // Page variables
    //
    // courseInstanceID is passed via POST from the add-classes-to-semester.php page
    //
    if(isset($_POST['courseInstanceID']) && isset($_POST['semesterID']))
    {
        $courseInstanceID = $_POST["courseInstanceID"];
        $semesterID = $_POST["semesterID"];
    }
    $showForm = true;

    // Checks to see if this page has been submitted to itsself. 
    // The variable is set in the form on this page.
    //
    $isSubmit = 0;
    $newClass = "";
    $newTeacher = "";
    $daysTaught = "";

    if(isset($_POST['isSubmit']))
    {
        $isSubmit = $_POST["isSubmit"];
    }

    if(isset($_POST['newClass']))
    {
        $newClass = $_POST["newClass"];
    }

    if(isset($_POST['newTeacher']))
    {
        $newTeacher = $_POST["newTeacher"];
    }

    if(isset($_POST['daysTaught']))
    {
        $daysTaught = $_POST["daysTaught"];
    }

    // classes, teachers, courseNameID, and instructorID will be filled in by data retrieved in the queries below
    //
    $classes = "";	
    $teachers = "";
    $courseNameID = "";
    $instructorID = "";

    $link = connect_db();

	if (isset($courseInstanceID))
	{    
		if ($isSubmit == 1)
 		{
			try
			{
				
				$insertQuery = "UPDATE CourseInstance  SET CourseID = '$newClass', InstructorID = '$newTeacher', DaysTaught = '$daysTaught' where InstanceID = '$courseInstanceID'";

				$result = mysql_query($insertQuery, $link);
				if($result===false)
				{
					$_SESSION['error']="Could not update class instance. - edit-course-instance.php";
					echo"<span style='color:red;'>Could not update to database.</span>";
				}
				else
				{
				    	$showForm = false;	
					echo "<form action='add-classes-to-semester.php' method='POST'>";
					echo "<input type='hidden' value='$semesterID' name='semesterID'>";
                    			echo "Course Instance successfully updated<br /><br />";
					echo "<input type='submit' value='Return to previous page'></form>";	
				}
			}
			catch (Exception $exception)
			{
				$_SESSION['error']=$exception->getMessage();
				echo $exception->getMessage();
			}
		}
	try
	{
		// SQL query that gets the information from multiple tables about the class instance to be edited.
		//
		$currentClassInstanceQuery = "select CourseInstance.InstanceID, Course.Name, Course.CourseID, User.UserID, User.FirstName, User.MiddleName,";
			$currentClassInstanceQuery.= " User.LastName, CourseInstance.DaysTaught from CourseInstance";
			$currentClassInstanceQuery .= " left join User on CourseInstance.InstructorID = User.UserID";
			$currentClassInstanceQuery .= " left join Course on CourseInstance.CourseID = Course.CourseID where CourseInstance.InstanceID =";
			$currentClassInstanceQuery .= " '$courseInstanceID'";

		// SQL query that gets the course ID and name of each course from the course table. 
		// Used in creating the list of options in the html element for selecting the class
		//
		$classQuery = "SELECT courseID, name FROM Course;";

		// SQL query that gets the teacher ID and full name of each teacher from the User table. 
		// Used in creating the list of options in the html element for selecting the teacher
		//
		$teacherQuery = "SELECT userid, FirstName, MiddleName, LastName FROM User where PrivilegeLevel = '2';";
		

		// actually run the queries using the provided link. Stores them in individual variables.
		//
		$currentClassInstanceResult = mysql_query($currentClassInstanceQuery, $link);
		$classQueryResult = mysql_query($classQuery, $link);
		$teacherQueryResult = mysql_query($teacherQuery, $link);

		// Load the Class Instance from the ID that was passed in
		//
		if($currentClassInstanceResult===false)
		{
			$_SESSION['error']="Could not get class instance details. - edit-course-instance.php";
		}
		else
		{
			while($classRow = mysql_fetch_array($currentClassInstanceResult, MYSQL_ASSOC))
			{	
				$courseInstanceID = $classRow["InstanceID"];
				$courseName = $classRow["Name"];
				$instructorName = $classRow["FirstName"]. " " . $classRow["MiddleName"]. " " . $classRow["LastName"];
				$daysTaught = $classRow["DaysTaught"];
				$courseNameID = $classRow["CourseID"];
				$instructorID = $classRow["UserID"];
			}
		}

		// Load all the classes from the Course table.
		// Stores the list of options in the variable $classes, to be printed inside the form.
		// Sets the current class as selected in the class list.
		//
		if($classQueryResult===false)
		{
			$_SESSION['error']="Could not get class details. - edit-semesters.php";
		}
		else
		{
			while($currentClassesRow = mysql_fetch_array($classQueryResult, MYSQL_ASSOC))
			{
				$printSelected ="";
				$listCourseID = $currentClassesRow["courseID"];
				$name = $currentClassesRow["name"];
				if ($courseNameID == $listCourseID){
					$printSelected = " selected='selected'";
				}
				$classes .= "<option value='$listCourseID'$printSelected>$name</option>";
			}
		}

		// Load all the teachers from the User table.
		// Stores the list of options in the variable $teachers, to be printed inside the form.
		// Sets the current Teacher as selected in the teachers list.
		//
		if($teacherQueryResult===false)
		{
			$_SESSION['error']="Could not get teacher details. - edit-semesters.php";
		}
		else
		{
			while($teachersRow = mysql_fetch_array($teacherQueryResult, MYSQL_ASSOC))
			{	
				$printSelected ="";
				$teacherID = $teachersRow["userid"];
				$firstName = $teachersRow["FirstName"];
				$middleName = $teachersRow["MiddleName"];
				$lastName = $teachersRow["LastName"];

				if ($instructorID == $teacherID) {
					$printSelected = " selected='selected'";
				}
				$teachers .= "<option value='$teacherID'$printSelected>$firstName $middleName $lastName</option>";
			}
		}
	}
	catch (Exception $exception)
	{
		$_SESSION['error']=$exception->getMessage();
		return false;
	}
	

	if ($showForm)
	{
?>
   	<form action="edit-course-instance.php" method="post">
	    <input type="hidden" value="<?php echo $courseInstanceID;?>" name="courseInstanceID">
	    <input type="hidden" value="<?php echo $semesterID;?>" name="semesterID">
	    <input type='hidden' name='isSubmit' value='1'>
	    <table id="addClasses" class="DataList" style="width:550px;">
		<thead>
			<tr>
				<th class="header" colspan="2">Edit the Class</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td class="rows">Select a Class:</td>
				<td class="rows">
				    <select name="newClass" style="width:250px" size="4">
					<?php echo $classes; ?>
				    </select>
				    <span style='color:red;'>&nbsp;*</span>
				</td>
			</tr>
			<tr>
				<td class="rows">Select a Teacher:</td>
				<td class="rows">
				    <select name="newTeacher" style="width:250px" size="4">
					<?php echo $teachers; ?>
				    </select>
				    <span style='color:red;'>&nbsp;*</span>
				</td>
			</tr>	
			<tr>
				<td class="rows">Days Taught:</td>
				<td class="rows">
				    <input name="daysTaught" style="width:250px;" value="<?php echo $daysTaught;?>">
				    <span style='color:red;'>*</span>
				</td>
			</tr>				
			<tr>
				<td colspan="2" class="rows" style="text-align:center;"><input type="submit" value="Update"></td>
			</tr>
		</tbody>
	    </table>
	</form>
<?php
		}
	}
	else {
	    echo "You must first visit <a href='manage-semesters.php'>this page</a> to choose a semester.";
	}
	endmasterpage();
?>
